import zipfile
import re

def parse_jupk(file_path):
    """
    解析 .jupk 文件，提取应用图标、包名和图标文件名
    :param file_path: .jupk 文件路径
    :return: 应用图标、包名、图标文件名、主引导文件内容
    """
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        # 查找主引导文件 InstallAppLog.f
        if 'InstallAppLog.f' not in zip_ref.namelist():
            raise ValueError("Invalid .jupk file: Missing InstallAppLog.f")

        # 读取主引导文件内容
        with zip_ref.open('InstallAppLog.f') as f:
            install_log = f.read().decode('utf-8')

        # 解析应用图标
        app_icon_pattern = re.compile(r'AppM=(.*?)=AppM')
        app_icon_match = app_icon_pattern.search(install_log)
        if not app_icon_match:
            raise ValueError("Invalid .jupk file: Missing AppM definition")
        app_icon = app_icon_match.group(1)

        # 解析应用包名（忽略 %g）
        app_package_pattern = re.compile(r'AppLj=%g(.*?)=AppLj')
        app_package_match = app_package_pattern.search(install_log)
        if not app_package_match:
            raise ValueError("Invalid .jupk file: Missing AppLj definition")
        app_package = app_package_match.group(1)

        # 解析图标文件名
        icon_pattern = re.compile(r'AppTb=(.*?)=AppTb')
        icon_match = icon_pattern.search(install_log)
        if not icon_match:
            raise ValueError("Invalid .jupk file: Missing AppTb icon definition")
        icon_filename = icon_match.group(1)

        # 检查图标文件是否存在
        if icon_filename not in zip_ref.namelist():
            raise ValueError(f"Invalid .jupk file: Icon file {icon_filename} not found")

        return app_icon, app_package, icon_filename, install_log